package com.ceadeal.admin.service;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.ceadeal.admin.vo.JPushVo;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.List;

/**
 * 功能描述: 发送极光推送消息
 * <p>
 * 作者: wyl
 * 日期: 2017/2/25 11:20
 */
@Service
@Transactional
public class JPushService {

    protected static final Logger log = LoggerFactory.getLogger(JPushService.class);

    @Value("${jpush.appKey}")
    private String appKey;

    @Value("${jpush.masterSecret}")
    private String masterSecret;

    @Autowired
    private Environment environment;

    @Autowired
    private ExecutorService executorService;

    private JPushClient jPushClient;

    public JPushClient getJPushClient() {
        if (jPushClient == null) {
            ClientConfig clientConfig = ClientConfig.getInstance();
            jPushClient = new JPushClient(appKey, masterSecret, null, clientConfig);
        }
        return jPushClient;
    }

    /**
     * 功能描述: 发送极光推送
     * @param
     * @return
     * @throws
     *
     * @author Yzw
     * @date 2017-03-09 20:06:53
     */
    public void sendPush(PushPayload ppl) {
        if (ppl == null) {
            return;
        }

        JPushClient jPushClient = getJPushClient();

        try {
            PushResult result = jPushClient.sendPush(ppl);
            log.info("Got result - " + result);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);

        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. " + e.getMessage());
        }
    }

    /**
     * 功能描述: 发送极光推送
     *
     * @param
     * @return
     * @throws
     * @author Yzw
     * @date 2017-02-25 17:26:18
     */
    public void sendPush(JPushVo jPushVo) {
        PushPayload pushPayload = this.buildPushPayload(jPushVo);
        executorService.executeCommand(() -> this.sendPush(pushPayload));
    }

    /**
     * 构建推送消息载体（如果别名和标签都为null，推送全部用户）
     *
     * @param jPushVo
     * @return PushPayload
     */
    public PushPayload buildPushPayload(JPushVo jPushVo) {
        return buildPushPayload(jPushVo.getTitle(), jPushVo.getAlert(), jPushVo.getAliases(), jPushVo.getTags(), jPushVo.getJsonExtra());
    }

    /**
     * 构建推送消息载体（如果别名和标签都为null，推送全部用户）
     *
     * @param title     标题
     * @param alert     提示信息
     * @param aliases   别名集合
     * @param tags      标签集合
     * @param jsonExtra JSON格式扩展数据
     * @return PushPayload
     */
    public PushPayload buildPushPayload(String title, String alert, List<String> aliases, List<String> tags, JsonObject jsonExtra) {
        // 参数处理
        title = StringUtils.isEmpty(title) ? "" : title;
        alert = StringUtils.isEmpty(alert) ? "" : alert;

        // 构建PushPayload.Builder
        PushPayload.Builder builder = PushPayload.newBuilder();

        // 设置平台
        builder.setPlatform(Platform.all());

        // 设置标签和别名
        Audience.Builder audienceBuilder = Audience.newBuilder();
        int ac = 0;
        if (tags != null && tags.size() > 0) {
            audienceBuilder.addAudienceTarget(AudienceTarget.tag(tags));
            ac++;
        }
        if (aliases != null && aliases.size() > 0) {
            audienceBuilder.addAudienceTarget(AudienceTarget.alias(aliases));
            ac++;
        }
        if (ac == 0) {
            builder.setAudience(Audience.all());
        } else {
            builder.setAudience(audienceBuilder.build());
        }

        // 设置通知
        // 构建Android通知
        AndroidNotification.Builder androidNoti = AndroidNotification.newBuilder();
        androidNoti.setAlert(alert);
        androidNoti.setTitle(title);
        if (jsonExtra != null) {
            androidNoti.addExtra("data", jsonExtra);
        }
        // 构建IOS通知
        IosNotification.Builder iosNoti = IosNotification.newBuilder();
        iosNoti.setSound("default");
        if (jsonExtra != null) {
            iosNoti.addExtra("data", jsonExtra);
        }
        // 构建全局通知
        Notification.Builder notiBuilder = Notification.newBuilder();
        notiBuilder.setAlert(alert);
        notiBuilder.addPlatformNotification(androidNoti.build());
        notiBuilder.addPlatformNotification(iosNoti.build());
        // SET
        builder.setNotification(notiBuilder.build());

        // 设置推送环境
//        if (!isDevelop()) {
            // 非开发环境的时候 要设置这个属性为正式环境  默认是开发环境
            builder.setOptions(Options.newBuilder().setApnsProduction(true).build());
//        }

        // 设置消息
        //builder.setMessage(Message.newBuilder().setTitle("title").setMsgContent("content").build());

        return builder.build();
    }

    /**
     * 功能描述: 是否为开发环境
     * @param
     * @return
     * @throws
     *
     * @author Yzw
     * @date 2017-03-09 19:48:08
     */
    public boolean isDevelop() {
        String[] profiles = environment.getActiveProfiles();
        for (String profile : profiles) {
            if (profile.contentEquals("dev")) {
                return true;
            }
        }
        return false;
    }
}
